/*
 * @lc app=leetcode.cn id=73 lang=javascript
 *
 * [73] 矩阵置零
 */

// @lc code=start
/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
var setZeroes = function (matrix) {
  let m = matrix.length;
  let n = matrix[0].length;
  let colZero = false;
  let rowZero = false;
  // 第一列是否包含0
  for (let i = 0; i < m; i++) {
    if (matrix[i][0] === 0) {
      colZero = true;
    }
  }
  // 第一行是否包含0
  for (let j = 0; j < n; j++) {
    if (matrix[0][j] === 0) {
      rowZero = true;
    }
  }
  // 循环除了第一列和第一行的元素，找到0后，将对应的行首和列首置成0
  for (let i = 1; i < m; i++) {
    for (let j = 1; j < n; j++) {
      if (matrix[i][j] === 0) {
        matrix[i][0] = matrix[0][j] = 0;
      }
    }
  }
  // 循环将行首和列首为0的元素置成0
  for (let i = 1; i < m; i++) {
    for (let j = 1; j < n; j++) {
      if (matrix[i][0] === 0 || matrix[0][j] === 0) {
        matrix[i][j] = 0;
      }
    }
  }

  // 判断列首是否有0
  if (colZero) {
    for (let i = 0; i < m; i++) {
      matrix[i][0] = 0;
    }
  }
  // 判断行首是否有0
  if (rowZero) {
    for (let j = 0; j < n; j++) {
      matrix[0][j] = 0;
    }
  }
};
// @lc code=end
